import { motion } from 'framer-motion';
import { useEffect, useState } from 'react';
import { getTagsAPI } from '@/api/tags.api';
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { TypeWriter } from "@/components/TypeWriter";
import { useDispatch, useSelector } from "react-redux";
import { getCategoryListAPI } from "@/api/category.api";
import { setQueryArticleList } from "@/store/article.store.ts";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { getAllArticleListAPI, getArticleListByCategoryAndTagAPI } from "@/api/article.api.ts";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";

function Blog() {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const [categoryActive, setcategoryActive] = useState<string>("all");
    const [categories, setCategories] = useState<Array<
        {
            _id: string;
            name: string;
            enName: string;
            createdAt: string;
            updatedAt: string;
        }
    >>([]);
    const [tags, setTags] = useState<Array<{
        _id: string;
        name: string;
        createdAt: string;
        updatedAt: string;
    }>>([]);
    const [activeTag, setActiveTag] = useState<string | null>(null);
    useEffect(() => {
        getAllArticleListAPI().then(res => {
            dispatch(setQueryArticleList(res.data.data))
        })
        getCategoryListAPI().then(res => {
            setCategories(res.data.data)
        })
        getTagsAPI(categoryActive).then(res => {
            setTags(res.data.data)
        })
        // 获取导航栏路由
        const router = window.location.pathname.split('/');
        // 当前激活分类
        if (router[2]) {
            setcategoryActive(router[2])
        }
        // 当前激活标签
        if (router[3]) {
            setActiveTag(router[3])
        }
    }, [dispatch, categoryActive])
    // 记录排序方式
    const [sortBy, setSortBy] = useState('date');
    // 从文章切片中获取文章列表
    const articles = useSelector((state: {
        articles: {
            queryArticleList: Array<{
                _id: string;
                title: string;
                cover: string;
                summary: string;
                updatedAt: string;
            }>
        }
    }) => state.articles.queryArticleList);

    const changeCategory = (category: {
        _id: string;
        name: string;
        enName: string;
        createdAt: string;
        updatedAt: string;
    }) => {
        setcategoryActive(category.enName)
        setActiveTag(null)
        navigate(`/blog/${category.enName}`)
        getArticleListByCategoryAndTagAPI(category._id, null).then(res => {
            dispatch(setQueryArticleList(res.data.data))
            console.log(articles);
        })
    }

    const changeTags = (tag: {
        _id: string;
        name: string;
        createdAt: string;
        updatedAt: string;
    }) => {
        setActiveTag(tag.name);
        navigate(`/blog/${categoryActive}/${tag.name}`);
        // 从categories 中获取category的_id
        const category_id = categories.find((category) => category.enName === categoryActive)?._id as string;
        getArticleListByCategoryAndTagAPI(category_id, tag._id).then(res => {
            dispatch(setQueryArticleList(res.data.data))
        })
    }
    return (
        <motion.div
            initial={{ opacity: 0, y: -50 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.2 }}
            className="w-full max-w-7xl m-auto mb-6">
            <div className="min-h-screen bg-gray-100">
                <div className="container mx-auto px-4 py-8 pt-16">
                    <header className="my-4">
                        <TypeWriter sentences={["You have to love yourself.", "I love you for my life past."]} />
                    </header>
                    <nav className="mb-8">
                        {/* 分类区域 */}
                        <Tabs value={categoryActive} className="w-full">
                            <TabsList className="w-full justify-start mb-4 overflow-x-auto">
                                {categories.map((category) => (
                                    <TabsTrigger
                                        key={category._id}
                                        value={category.enName}
                                        onClick={(e) => {
                                            e.preventDefault();
                                            changeCategory(category)
                                        }}
                                        className="!rounded-button whitespace-nowrap"
                                    >
                                        {category.name}
                                    </TabsTrigger>
                                ))}
                            </TabsList>
                        </Tabs>
                        {/* 标签区域 */}
                        <div className="flex flex-wrap gap-2">
                            {tags.map((tag) => (
                                <Button
                                    key={tag._id}
                                    variant="outline"
                                    className={`!rounded-button whitespace-nowrap font-code tag ${activeTag === tag.name ? "text-themeEnglishLight bg-smallLightArea dark:text-themeEnglishDark dark:bg-smallDarkArea" : ""
                                        }`}
                                    onClick={(e) => {
                                        e.preventDefault();
                                        changeTags(tag)
                                    }}
                                >
                                    {tag.name}
                                </Button>
                            ))}
                        </div>
                    </nav>
                    {/* 排序方式 */}
                    <div className="flex justify-end mb-4">
                        <Select value={sortBy} onValueChange={setSortBy}>
                            <SelectTrigger className="w-[180px] !rounded-button">
                                <SelectValue placeholder="排序方式" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="date">按发布时间排序</SelectItem>
                                <SelectItem value="popularity">按热度排序</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                    {/* 主要内容区域 */}
                    <main>
                        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                            {articles.map((article) => (
                                <div key={article._id} className="break-inside-avoid mb-6">
                                    <Card
                                        className="hover:shadow-md transition-shadow cursor-pointer bg-bigLightArea dark:bg-bigDarkArea rounded-none h-fit"
                                        onDoubleClick={() => {
                                            navigate(`/currentArticle/${article._id}`)
                                        }}
                                    >
                                        <img src={article.cover} alt={article.title} className="w-[160px] h-[90px] rounded-t-none hover:scale-110 transition-transform overflow-hidden object-cover" />
                                        <CardHeader>
                                            <CardTitle>{article.title}</CardTitle>
                                        </CardHeader>
                                        <CardContent>
                                            <p className="text-sm text-gray-600 mb-2">{article.summary}</p>
                                            <div className="flex justify-between items-center text-sm text-gray-500">
                                                <span className="font-code">{article.updatedAt}</span>
                                            </div>
                                        </CardContent>
                                    </Card>
                                </div>
                            ))}
                        </div>
                    </main>
                    {/* loading */}
                    <div className="mt-8 flex justify-center">
                        <Button className="!rounded-button whitespace-nowrap" onClick={() => console.log('加载更多')}>
                            加载更多
                        </Button>
                    </div>
                </div>
            </div>
        </motion.div>
    )
}

export default Blog